package com.rongc.client.freight.business.supply.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.rongc.client.core.exception.RegexException;
import com.rongc.client.core.network.code.HandleCode;
import com.rongc.client.core.network.http.RequestManager;
import com.rongc.client.core.utils.ActivityUtils;
import com.rongc.client.core.utils.FileUtil;
import com.rongc.client.core.utils.RegexUtil;
import com.rongc.client.core.utils.SystemUtil;
import com.rongc.client.freight.R;
import com.rongc.client.freight.UniApplication;
import com.rongc.client.freight.base.BaseActivity;
import com.rongc.client.freight.base.model.ProvinceList;
import com.rongc.client.freight.base.model.TipTemp;
import com.rongc.client.freight.base.view.activity.CarLengthActivity;
import com.rongc.client.freight.base.view.activity.CarModeActivity;
import com.rongc.client.freight.base.view.activity.MapGdActivity;
import com.rongc.client.freight.base.view.widget.CJRow.ARResponse;
import com.rongc.client.freight.base.view.widget.CJRow.CJRow;
import com.rongc.client.freight.base.view.widget.CJRow.CJRowListener;
import com.rongc.client.freight.base.view.widget.CJRow.CustomCJRowAdapter;
import com.rongc.client.freight.base.view.widget.CJRow.ViewBinder;
import com.rongc.client.freight.base.view.widget.wheelwidget.Time2PickerView;
import com.rongc.client.freight.business.supply.buz.SupplyBuz;
import com.rongc.client.freight.business.supply.model.SupplyDic;
import com.rongc.client.freight.business.supply.request.api.SupplyCreateApi;
import com.rongc.client.freight.utils.UtilMethod;
import com.rongc.client.freight.utils.dic.IField;
import com.rongc.client.freight.utils.dic.impl.Field;
import com.rongc.client.freight.utils.dic.impl.Table;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;

import static com.rongc.client.freight.base.model.DicsBean.DicBean;

/**
 * Created by ccqx on 2017/7/1.
 */

public class SupplyCreateActivity extends BaseActivity implements View.OnClickListener{
    @Bind(R.id.cjrow)
    CJRow mRow;
    @Bind(R.id.tv_totle)
    TextView mTvTotle;
    CustomCJRowAdapter baseAdapter;
    Table table_base;
    ARResponse response;
    Time2PickerView pvOptionsProvince;
    @OnClick({R.id.btn_submit})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                try{
                    prepare();
                    SupplyCreateApi p = new SupplyCreateApi(new SupplyCreateApi.SupplyCreateParams(response.getData()),
                            respWorkersListener, errorListener);
                    RequestManager.getInstance().call(p);
                }catch (RegexException e){
                    ActivityUtils.toast(e.getMessage());
                }


                break;
        }
    }

    void prepare() throws RegexException {
        if(!RegexUtil.checkNotNull(response.getValue("loadTime"))){
            throw new RegexException("请选择装货时间");
        }else if(!RegexUtil.checkNotNull(response.getValue("startPlace"))){
            throw new RegexException("请选择出发地");
        }else if(!RegexUtil.checkNotNull(response.getValue("endPlace"))){
            throw new RegexException("请选择目的地");
        }else if(!RegexUtil.checkNotNull(response.getValue("carLength"))){
            throw new RegexException("请选择车长");
        }else if(!RegexUtil.checkNotNull(response.getValue("carModels"))){
            throw new RegexException("请选择车型");
        }else if(!RegexUtil.checkNotNull(response.getValue("goods"))){
            throw new RegexException("请选择货物名称");
        }else if(!RegexUtil.checkNotNull(response.getValue("weights"))){
            throw new RegexException("请选择货物重量");
        }else if(!RegexUtil.checkNotNull(response.getValue("dilk"))){
            throw new RegexException("请选择货物体积");
        }/*else if(!RegexUtil.checkNotNull(response.getValue("message"))){
            throw new RegexException("请输入留言");
        }*/

    }

    Response.Listener<JSONObject> respWorkersListener = new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            if (HandleCode.requestSuccess()) {
                String goodid = null;
                try {
                    goodid = response.getString("goodId");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                ActivityUtils.toast(HandleCode.headerMessage);
                FileUtil.clearDir(FileUtil.getTempFile());
                finish();

                Bundle bundle = new Bundle();
                bundle.putString("data",goodid);
                ActivityUtils.startActivity(SupplyCreateActivity.this,SupplyWaybillActivity.class,bundle);
            } else {
                UtilMethod.dismissProgressDialog(SupplyCreateActivity.this);
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            UtilMethod.dismissProgressDialog(SupplyCreateActivity.this);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode){
                case  SupplyDic.ResultType.Model_TYPE:
                    DicBean dataStr = (DicBean) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("carModels",dataStr.getKey());
                    baseAdapter.notifyDataSetChanged();
                    break;
                case  SupplyDic.ResultType.Length_TYPE:
                    dataStr = (DicBean) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("carLength",dataStr.getKey());
                    baseAdapter.notifyDataSetChanged();
                    break;
                case SupplyDic.ResultType.DEPARTURE_TYPE:
                    TipTemp result = (TipTemp) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("startPlace",result.getAddress());
                    baseAdapter.setFieldvalue("startLon",result.getLongitude() +"");
                    baseAdapter.setFieldvalue("startLat",result.getLatitude() +"");
                    baseAdapter.notifyDataSetChanged();
                    break;
                case SupplyDic.ResultType.DESTINATION_TYPE:
                    result = (TipTemp) data.getSerializableExtra("data");
                    baseAdapter.setFieldvalue("endPlace",result.getAddress());
                    baseAdapter.setFieldvalue("endLon",result.getLongitude() +"");
                    baseAdapter.setFieldvalue("endLat",result.getLatitude() +"");
                    baseAdapter.notifyDataSetChanged();
                    break;
                case  SupplyDic.ResultType.MESSAGE_TYPE:
                    String str = data.getStringExtra("data");
                    baseAdapter.setFieldvalue("message",str);
                    baseAdapter.notifyDataSetChanged();
                    break;
            }
            mTvTotle.setText(Html.fromHtml(String.format(getResources().getString(R.string.supply_create_total),"0")));
        }
    }

    @Override
    public void initView() {
        initToolbar(R.string.supply_create_title);
        pvOptionsProvince = new Time2PickerView(this);
        mTvTotle.setText(Html.fromHtml(String.format(getResources().getString(R.string.supply_create_total),"0")));

    }

    @Override
    public void initData() {

        response = SupplyBuz.getMockBaseResponse();
        response.update("userId", UniApplication.getInstance().getUserInfo().getUserId());

        table_base = SupplyBuz.getJBXXTable(this);
        baseAdapter = new CustomCJRowAdapter(this, mRow,table_base, response);
        mRow.setAdapter(baseAdapter);

        baseAdapter.setViewBinder(new ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, int position, String from) {
                /*if("loadTime".equals(from)){
                    if(StringUtils.isNotEmpty((String)data)) {
//                        String sDate = DateUtil.getStringByFormat((String) data, DateUtil.dateFormatMDHM_china);
                        ((TextView)view.findViewById(R.id.lablevalue)).setText((String)data);
                    }
                }else */if("message".equals(from)){
                    ((TextView)view.findViewById(R.id.lablevalue)).setText("");
                }
                return false;
            }
        });
        baseAdapter.setCJRowListener(new CJRowListener() {
            @Override
            public boolean seedAction(int location, Field field, Object obj) {
                return false;
            }

            @Override
            public boolean activityAction(Field field, Object obj) {
                if("carModels".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(SupplyCreateActivity.this,CarModeActivity.class, SupplyDic.ResultType.Model_TYPE);
                }else if("carLength".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(SupplyCreateActivity.this,CarLengthActivity.class, SupplyDic.ResultType.Length_TYPE);
                }else if("startPlace".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(SupplyCreateActivity.this,MapGdActivity.class, SupplyDic.ResultType.DEPARTURE_TYPE);
                }else if("endPlace".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(SupplyCreateActivity.this,MapGdActivity.class, SupplyDic.ResultType.DESTINATION_TYPE);
                }else if("message".equals(field.getFieldName())){
                    ActivityUtils.startActivityForResult(SupplyCreateActivity.this,SupplyCreateMessageActivity.class, SupplyDic.ResultType.MESSAGE_TYPE);
                }
                return true;
            }

            @Override
            public boolean popupWindowAction(final IField field, Object obj) {
                if("loadTime".equals(field.getFieldName())){
                    SystemUtil.hideSystemKeyboad(SupplyCreateActivity.this);
                    pvOptionsProvince.setPicker(ProvinceList.getOptions1Items(), ProvinceList.getOptions2Items(), ProvinceList.getOptions3Items(), true);
                    pvOptionsProvince.setCyclic(false, false, false);
                    pvOptionsProvince.setSelectOptions(0, 0, 0);
                    pvOptionsProvince.setOnoptionsSelectListener(new Time2PickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {
                            //返回的分别是三个级别的选中位置
                            String tx = ProvinceList.getOptions1Items().get(options1).getName()+" "
                                    + ProvinceList.getOptions2Items().get(option2)+ ":"
                                    + ProvinceList.getOptions3Items().get(options3)+ ":00";
                            baseAdapter.setFieldvalue(field.getFieldName(),tx);
                            baseAdapter.notifyDataSetChanged();
                        }
                    });
                    pvOptionsProvince.show();
                }
                return true;
            }
        });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_supply_create;
    }
}
